package com.code.common.page;

import java.io.IOException;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

@SuppressWarnings("serial")
public class PageTag extends BodyTagSupport {

    protected String page;

    protected String url;

    protected String formname = "forms[0]";

    private StringBuffer sbPage = null;

    /**
     * 
     */
    @SuppressWarnings("unchecked")
    public int doStartTag() throws JspException {
	JspWriter out = pageContext.getOut();
	Pagination c = (Pagination) this.pageContext.findAttribute(page);

	/**if (c == null || c.getTotalCount() == 0) {
		return SKIP_BODY;
	}**/

	int pageNo = c.getCurrentPage();
	int pageSize = c.getCount();
	int recordCount = c.getTotalCount();
	int totalpage = c.getTotalPage();

	sbPage = new StringBuffer();
	// String root = ((HttpServletRequest)
	// this.pageContext.getRequest()).getContextPath();
	// addLine("<input type=\"hidden\" name=\"" + Constants.PAGE_CURRENT +
	// "\" value=\"" + pageNo + "\">");

	addLine(makeScript(recordCount, pageSize, pageNo, totalpage));
	addLine("<script language=\"JavaScript\" type=\"text/JavaScript\">");
	addLine("   function go(page) {");
	addLine("       if (!isSubmit()) {");
	addLine("           return false;");
	addLine("       }");
	addLine("       if (isNum(page)) {");
	addLine("           document." + formname + "." + "currentPage"  + ".value=page;");//Constants.PAGE_CURRENT + ".value=page;");
	if (url != null && url.length() > 0) {
	    addLine("       document.action = " + url);
	}
	addLine("           document." + formname + ".submit();");
	// addLine("           setSubmit();");
	addLine("        } else{");
	addLine("            alert(\" 请输入数字！\");");
	addLine("        }");
	addLine("   }");

	addLine("</script>");

	try {
	    out.println(sbPage.toString());
	} catch (IOException e) {
	    throw new JspException(e);
	}

	sbPage = null;

	return EVAL_PAGE;

    }

    /**
     * 
     * @param str
     */
    private void addLine(String str) {
	sbPage.append(str + "\n");
    }

    /**
     * 
     * @param map
     * @param key
     * @return
     */
    @SuppressWarnings( { "unused", "unchecked" })
    private int getIntValue(Map map, String key) {

	int i = 0;

	if (map.get(key) != null) {
	    i = ((Integer) map.get(key)).intValue();
	}

	return i;

    }

    private String makeScript(int totalRecordNumber, int pageSize, int currentPage, int totalPage) {

	StringBuffer sHTML = new StringBuffer();
	sHTML
		.append("<TABLE border=0 cellPadding=0 cellSpacing=0 width=100% class=\"reportbar\" align=\"center\">"
			+ "\r\n");
	sHTML.append("<TR>" + "\r\n");
	// 共有 ? 条记录，第?/?页
	// sHTML.append("<TD class=\"t4\" style=\"text-align: right;vertical-align: middle;padding-right:mm px;\" width=\"38%\" >&nbsp; 共有<u><font color=#ff0000 >");
	// sHTML.append( totalRecordNumber + "</font></u>条记录，第" + currentPage +
	// "/" + totalPage + "页 </TD>" + "\r\n");

	sHTML
		.append("<TD class=\"t4\" style=\"text-align: right;vertical-align: middle;padding-right:mm px;padding-top:2px;\" width=\"38%\" >&nbsp;");
	sHTML.append("<span>共</span><span>");
	sHTML.append(totalRecordNumber + "</span><span>条</span><span>|</span><span>页数：" + currentPage + "/"
		+ totalPage + "</span>&nbsp;" + "\r\n");

	// 首页,上一页
	if (currentPage > 1) {
	    sHTML.append("<span><a href='javascript:go(1);' class='t1'>首 页</a></span>&nbsp;" + "\r\n");
	    sHTML.append("<span><a href='javascript:go(" + (currentPage - 1)
		    + ");'  class='t1'>上一页</a></span>&nbsp;" + "\r\n");
	}

	if (currentPage < totalPage) {
	    sHTML.append("<span><a href='javascript:go(" + (currentPage + 1)
		    + ");'  class='t1'>下一页</a></span>&nbsp;" + "\r\n");
	    sHTML.append("<span><a href='javascript:go(" + totalPage + ");' class='t1'>末 页</a></span>&nbsp;"
		    + "\r\n");
	}

	sHTML.append("<script>" + "\r\n");
	sHTML.append(" function gotopage(firstpageno,lastpageno){" + "\r\n");
	sHTML.append("      var gotopageno = document.getElementById(\"gotopageno\").value;" + "\r\n");
	sHTML.append("      if(gotopageno < firstpageno || gotopageno > lastpageno){" + "\r\n");
	sHTML
		.append("          alert(\"请输入正确的页号,范围从[\"+firstpageno+\"]\"+\"到[\"+lastpageno+\"]\");"
			+ "\r\n");
	sHTML.append("          document.getElementById(\"gotopageno\").focus();" + "\r\n");
	sHTML.append("          return ;" + "\r\n");
	sHTML.append("      } else {" + "\r\n");
	sHTML.append("          go(gotopageno);}" + "\r\n");
	sHTML.append(" }" + "\r\n");
	sHTML.append("\r\n");
	sHTML.append("var ns=false;" + "\r\n");
	sHTML.append("var ie=false;" + "\r\n");
	sHTML.append("var BrowName = navigator.appName;" + "\r\n");
	sHTML.append("if (BrowName.indexOf(\"Microsoft Internet Explorer\") != -1)" + "\r\n");
	sHTML.append("ie=true;" + "\r\n");
	sHTML.append("if (BrowName.indexOf(\"Netscape\") != -1)" + "\r\n");
	sHTML.append("ns=true;" + "\r\n");
	sHTML.append("if (ns) document.captureEvents(Event.KEYDOWN);" + "\r\n");
	sHTML.append("function keyDown(e){" + "\r\n");
	sHTML.append("  var keyValue;" + "\r\n");
	sHTML.append("  if(ns) {" + "\r\n");
	sHTML.append("      keyValue=e.which;" + "\r\n");
	sHTML.append("  }" + "\r\n");
	sHTML.append("  if(ie) {" + "\r\n");
	sHTML.append("      keyValue=event.keyCode;" + "\r\n");
	sHTML.append("  }" + "\r\n");
	sHTML.append("  if(keyValue==13) {");
	sHTML.append("      gotopage(1," + totalPage + ")");
	sHTML.append("  }" + "\r\n");
	sHTML.append("}" + "\r\n");
	sHTML.append("</script>" + "\r\n");

	if (totalRecordNumber > pageSize) {
	    sHTML
		    .append("<span>转到</span> <div class='pnumberss'><input type=\"text\"  size=\"3\" id=\"gotopageno\"  name=\"gotopageno\"  value="
			    + currentPage + " onkeydown=\"keyDown(event);\" ></div> " + "\r\n");
	    sHTML.append("<span ><a href='javascript:gotopage(1," + totalPage
		    + ");'  class='t1'>跳转</a></span>" + "\r\n");
	    // sHTML.append("<span id='pagesgo'><a href=\"#\" onclick=\"javascript:gotopage(1,"+
	    // totalPage + ")\">" + "跳转" + "</a></span>\r\n");
	}
	sHTML.append("<input type=\"text\"  name=\"t1\" style=\"DISPLAY: none\">" + "\r\n");
	sHTML.append("</TD></TR></TABLE>" + "\r\n");

	return sHTML.toString();
    }

    /**
     * @return
     */
    public String getUrl() {
	return url;
    }

    /**
     * @param string
     */
    public void setUrl(String string) {
	url = string;
    }

    /**
     * @return
     */
    public String getFormname() {
	return formname;
    }

    /**
     * @param string
     */
    public void setFormname(String string) {
	formname = string;
    }

    public String getPage() {
	return page;
    }

    public void setPage(String page) {
	this.page = page;
    }

}